import { FormInstance, Rule } from 'ant-design-vue/es/form'
import { regex } from 'g6-fn'
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { studentsManageApi } from '@/services/api/aigc-admin'

export interface FormState {
  inviteNoticeId?: string
  username?: string
  number?: string
  tel?: string
}

export const useForm = () => {
  const formRef = ref<FormInstance>()
  const confirmLoading = ref(false)
  // 是否需要审核
  const needCheck = ref(false)
  const successful = ref(false)
  const route = useRoute()
  const router = useRouter()
  const targetName = ref('')

  const formState = reactive<FormState>({
    inviteNoticeId: undefined,
    username: '',
    number: '',
    tel: ''
  })

  const rules: Record<string, Rule[]> = {
    username: [
      { required: true, message: '请输入学生姓名', trigger: 'change' },
      {
        pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,20}$/,
        message: '请输入正确的学生姓名'
      }
    ],
    number: [
      { required: true, message: '请输入学号', trigger: 'change' },
      {
        pattern: /^\d{1,20}$/,
        message: '请输入正确的学号'
      }
    ],
    tel: [
      { required: true, message: '请输入手机号', trigger: 'change' },
      { pattern: regex.phone, message: '请输入正确的手机号' }
    ]
  }

  const submit = async () => {
    try {
      await formRef.value?.validate()
      changeConfirmLoading(true)

      const { data } = await studentsManageApi.join(formState)
      needCheck.value = data
      successful.value = true
    } catch (error) {
      console.log(error)
    } finally {
      changeConfirmLoading(false)
    }
  }

  const changeConfirmLoading = (bool: boolean) => {
    confirmLoading.value = bool
  }

  // 校验链接合法性
  const checkLink = async () => {
    const code = route?.query?.inviteCode as string
    if (!code) return router.push('/404')
    try {
      const { data } = await studentsManageApi.checkLink({}, { urlParams: { code } })
      formState.inviteNoticeId = data.id
      targetName.value = data.fullOrgName
    } catch (error: any) {
      if (error?.code === 'AUTH-100071') {
        router.push('/404')
      }
    }
  }

  onMounted(() => {
    document.title = 'AIGC实训平台-邀请加入'
    const app = document.querySelector('#app')
    app?.setAttribute('style', 'min-width: 0')
    checkLink()
  })

  onUnmounted(() => {
    document.title = '第六镜人工智能教学实训平台'
    const app = document.querySelector('#app')
    app?.setAttribute('style', 'min-width: 1024px')
  })

  return {
    targetName,
    successful,
    formRef,
    needCheck,
    rules,
    formState,
    submit,
    confirmLoading,
    changeConfirmLoading
  }
}
